package com.sample.service;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class JmsSender {
   private JmsTemplate jmsTemplate;
   private Destination topic;
   private boolean isRunning = false;

   public JmsSender(JmsTemplate template, Destination topic) {
      this.jmsTemplate = template;
      this.topic = topic;
      //run();
   }

   private void run() {
      if (!isRunning) {
         while (true) {
            publish();
            try {
               Thread.sleep(10000);
            } catch (InterruptedException e) {
               e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
         }
      }
   }

   public void publish() {
      if (jmsTemplate != null) {
         jmsTemplate.send(topic, new MessageCreator() {
            public Message createMessage(Session transaction) throws JMSException {
               Calendar cal = Calendar.getInstance();
               SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
               String testMessage = sdf.format(cal.getTime());
               System.out.println("Sending message...." + testMessage);
               EventMetadata eventMetadata = new EventMetadata();
               eventMetadata.setProcessName("Process Name");
               eventMetadata.setProcessType("Process Type");
               eventMetadata.setStartDate(cal.getTime());
               final Message message = transaction.createObjectMessage(eventMetadata);
               return message;
            }
         });
      }
   }

}
